package com.second.app.thread.reentrant.consumerproduce;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gyz
 * @date 2021/2/2 10:26
 */
public class ConsumerProduce {
    private final ReentrantLock reentrantLock = new ReentrantLock();

    public Condition condition = reentrantLock.newCondition();

    private volatile Boolean hasValue = false;

    public volatile Integer commonValue;

    public Integer getCommonValue() {
        return commonValue;
    }

    public void setCommonValue(Integer commonValue) {
        this.commonValue = commonValue;
    }

    /**
     * 生产
     */
    public void set() {
        reentrantLock.lock();
        try {
            if (hasValue) {
                condition.await();
            }
            int random = (int) (Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + "生产值:" + random);
            setCommonValue(random);
            hasValue = true;
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }

    /**
     * 消费
     */
    public void get() {
        reentrantLock.lock();
        try {
            if (!hasValue) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "消费值:" + getCommonValue());
            hasValue = false;
            //通知生产线程生产;
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}
